/*
 * @Description: 封装axios请求(上传文件)
 * @version:
 * @Author: m
 * @LastEditors: m
 */

import axios from "axios";
// import Qs from "qs";
import { Toast } from "vant";
import { getToken } from "@/utils/auth";
import global_url from "@/utils/global";
import router from "../router";

const serviceFile = axios.create({
	baseURL: global_url.httpUrl,
	timeout: 60 * 1000,
	headers: { "Content-Type": "multipart/form-data" },
	withCredentials: true,
});

serviceFile.interceptors.request.use(
	(config) => {
		// config.data = Qs.stringify(config.data);
		// config.data = config.data + "&token=" + getToken();
		config.headers.OAUTH_BEARER_TOKEN = getToken().token;
		return config;
	},
	(error) => {
		console.log(error);
		return Promise.reject(error);
	}
);

serviceFile.interceptors.response.use(
	(response) => {
		const res = response.data;

		if (res.code != 200) {
			if (res.code == 300) {
				Toast.fail(res.message);
				return res;
			} else if (res.code == 301) {
				removeToken();
				router.push("/login");
				return res;
			} else if (res.code == 500) {
				Toast.fail("服务器异常!");
				return Promise.reject();
			} else if (res.code == 400) {
				Toast.fail("请求错误!");
				return Promise.reject();
			} else {
				return res;
			}
		} else {
			console.log(res);
			return res;
		}
	},
	(error) => {
		Toast.fail("网络连接错误");
		return Promise.reject(error);
	}
);

export default serviceFile;
